package com.db.controller;

import com.db.entity.Person;
import com.db.service.PersonService;
import com.db.service.impl.PersonServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/selectPerson")
public class SelectPersonController extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        HttpSession session = request.getSession();

        String type = (String)request.getAttribute("type");
        String types = (String)session.getAttribute("type");
        String value = (String)request.getAttribute("value");

        String values= (String)session.getAttribute("value");

        if(values != null) value=values;
        if(types != null)type = types;

        if ("".equals(value)){
            response.sendRedirect(request.getContextPath()+"/showPersons");
            return;
        }

        String username = (String)session.getAttribute("login");
        Integer userid = (Integer)session.getAttribute("userid");
        if( username == null){
            response.sendRedirect(request.getContextPath()+"/login.jsp");
            return;
        }
        PersonService ps = new PersonServiceImpl();
        Integer pageIndex = 1;

        String str = request.getParameter("pageIndex");
        if(str != null)pageIndex = Integer.parseInt(str);

        request.setAttribute("pageIndex",pageIndex);

        List<Person> list =new ArrayList<>();
        List<Person> list1 = new ArrayList<>();
        if("name".equals(type)){

            list = ps.retrieveByName(pageIndex,value,userid);
            list1 = ps.retrieveByNameNo(value,userid);

        }else if("mobile".equals(type)){

            list = ps.retrieveByMobile(pageIndex,value,userid);
            list1 = ps.retrieveByMobileNo(value,userid);
        }else if("address".equals(type)){
            list = ps.retrieveByAddress(pageIndex,value,userid);
            list1 = ps.retrieveByAddressNo(value,userid);
        }

        Integer maxpage = 0;
        if (list1.size()%5==0) {
            maxpage =list1.size()/5;
        }else{
            maxpage = list1.size()/5+1;
        }


        request.setAttribute("maxPage",maxpage);
        if(type != null)
        session.setAttribute("type",type);
        if(!"".equals(value))
            session.setAttribute("value",value);
        request.setAttribute("Persons",list);
        request.getRequestDispatcher("/showAllPerson.jsp").forward(request,response);






    }
}
